package testPaperCTCS;

import android.app.Activity;
import android.content.Context;
import android.graphics.drawable.ColorDrawable;
import android.os.Build;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.example.lancooznbk.R;
import com.example.lancooznbk.utils.DensityUtils;
import com.example.lancooznbk.view.base.BaseActivity;
import com.example.lancooznbk.view.widget.QuesIndexView;

import lancooControl.Control;
import lancooCustomListview.BounceScrollView;

import static lancooUpLoad.PaperInfor.isfirstSubmit;
import static testPaperCTCS.GuessTestingPaperActivity.InforGuessTesting;
import static testPaperCTCS.GuessTestingPaperActivity.VpGuessTestingPaper;


/**
 * Created by Administrator on 2017/3/14.
 */
public class GuessTestingAnswerSheet extends PopupWindow {

    private View mMenuView;
    private RelativeLayout RLayoutBackMenu;
//    private TextView TvClose;
    private TextView TvTitle;
    private LinearLayout LayoutAssess;
    private TextView TvAllScore;
    private TextView TvUseTime;
    private Button BtnCheckAllAnalysis;//查看全部解析

    private BounceScrollView mScrollView;

    TextView[] TvTypeName;

    private Activity mContext;

    private int mCurPageIndex;
    private int mCurQuesIndex;



    public GuessTestingAnswerSheet(Activity context,int curPageIndex,int curQuesIndex) {
        super(context);
        this.mCurPageIndex = curPageIndex;
        this.mCurQuesIndex = curQuesIndex;
        LayoutInflater inflater = (LayoutInflater) context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        mMenuView = inflater.inflate(R.layout.answer_sheet, null);

        //核心代码.
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            context.getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        }

        mContext = context;

        RLayoutBackMenu = (RelativeLayout) mMenuView.findViewById(R.id.rlayout_back_menu);
        //取消按钮
//        TvClose = (TextView) mMenuView.findViewById(R.id.tv_close);

        mScrollView = (BounceScrollView) mMenuView.findViewById(R.id.scroll_ques_index);

        RelativeLayout relToolbar = (RelativeLayout) mMenuView.findViewById(R.id.rlayout_back);
        int statusBarHeight = ((BaseActivity) context).getStatusBarHeight();
        RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) relToolbar.getLayoutParams();
        layoutParams.setMargins(0,statusBarHeight,0,0);

        RLayoutBackMenu.setOnClickListener(new OnClickListener() {

            public void onClick(View v) {
                //销毁弹出框
                dismiss();
                if (BtnCheckAllAnalysis.getVisibility() == View.VISIBLE){
                    mContext.finish();
                }
            }
        });

//        TvClose.setOnClickListener(new OnClickListener() {
//
//            public void onClick(View v) {
//                //销毁弹出框
//                dismiss();
//            }
//        });

        //答题卡标题文字
        TvTitle = (TextView) mMenuView.findViewById(R.id.tv_tittle);
        //联系报告自评内容
        LayoutAssess = (LinearLayout) mMenuView.findViewById(R.id.layout_assess);
        //总得分
        TvAllScore = (TextView) mMenuView.findViewById(R.id.tv_all_score);
        //用时
        TvUseTime = (TextView) mMenuView.findViewById(R.id.tv_use_time);
        //查看全部解析
        BtnCheckAllAnalysis = (Button) mMenuView.findViewById(R.id.btn_check_all_analysis);


        //设置SelectPicPopupWindow的View
        this.setContentView(mMenuView);
        //设置SelectPicPopupWindow弹出窗体的宽
        this.setWidth(LayoutParams.FILL_PARENT);
        //设置SelectPicPopupWindow弹出窗体的高
        this.setHeight(LayoutParams.FILL_PARENT);
        //设置SelectPicPopupWindow弹出窗体可点击
        this.setFocusable(true);
        //设置SelectPicPopupWindow弹出窗体动画效果
        this.setAnimationStyle(R.style.Popupwindow);
        //实例化一个ColorDrawable颜色为半透明
        ColorDrawable dw = new ColorDrawable(0xb0000000);
        //设置SelectPicPopupWindow弹出窗体的背景
        this.setBackgroundDrawable(dw);

        LinearLayout LayoutAnswerSheet = (LinearLayout) mMenuView.findViewById(R.id.layout_answer_sheet);
        int sumPaperCount = InforGuessTesting.getPaperContent().size();
        Double stuScore = 0.0;
        Double allScore = 0.0;

        String strTypeName = "";
        TvTypeName = new TextView[sumPaperCount];
        RelativeLayout[] RLayoutQuesList = new RelativeLayout[sumPaperCount];
        for(int i=0;i<sumPaperCount;i++){
            strTypeName = InforGuessTesting.getPaperContent().get(i).getTypeName();
            TvTypeName[i] = new TextView(mContext);
            TvTypeName[i].setText(String.valueOf(i+1)+"."+strTypeName);
            TvTypeName[i].setPadding(DensityUtils.dp2px(mContext,15), DensityUtils.dp2px(mContext,15),0,DensityUtils.dp2px(mContext,15));
            LayoutAnswerSheet.addView(TvTypeName[i]);
            RLayoutQuesList[i] = new RelativeLayout(mContext);
            //RLayoutQuesList[i].setPadding(0,10,0,20);

            int sumTotalItemCount = InforGuessTesting.getPaperContent().get(i).getTotalItemCount();
            DisplayMetrics dm = new DisplayMetrics();
            context.getWindowManager().getDefaultDisplay().getMetrics(dm);
            int width = dm.widthPixels;
            int height = dm.heightPixels;

            final QuesIndexView[] quesIndexViews = new QuesIndexView[sumTotalItemCount];
            //Button[] BtnQuesNumber = new Button[sumTotalItemCount];
            int k = -1;

            int sumOfQuesKong = 0;//单道大题的总空数
            for(int p=0;p<sumTotalItemCount;p++){
                sumOfQuesKong = sumOfQuesKong+Control.backSum(InforGuessTesting.getPaperContent().get(i).getQueList().get(p).getAnswer(),"$、")+1;
            }

            for(int j = 0;j<sumTotalItemCount;j++){

                    //BtnQuesNumber[j] = new Button(mContext);
                quesIndexViews[j] = new QuesIndexView(mContext);
                quesIndexViews[j].setTag(j);
                if ( i == mCurPageIndex && j == mCurQuesIndex){
                    quesIndexViews[j].setQuesIndexChecked(true);
                    mScrollView.post(new Runnable() {
                        @Override
                        public void run() {
                            // int[] location = new int[2];
                            int top1 = TvTypeName[mCurPageIndex].getTop();
                            top1 -= 10;
                            // int top = (rLayoutQuesList[mCurPageIndex].findViewWithTag(mCurQuesIndex)).getTop();
                            if (top1 < 0){
                                top1 = 0;
                            }
                            mScrollView.scrollTo(0,top1);
                        }
                    });

                }

                if(InforGuessTesting.getState()==2) {
                    //已提交
                    if (!GetStuAssess(i, j).equals("")) {
                        //自评不为空
//                        int sumOfRight = Control.backSum(GetStuAssess(i, j),"正确")+Control.backSum(GetStuAssess(i, j),"优秀")+Control.backSum(GetStuAssess(i, j),"一般");

                        int sumOfQuestion = Control.backSum(GetAnswer(i,j),"$、")+1;
                        String stuAssessOfQuestion = InforGuessTesting.getPaperContent().get(i).getQueList().get(j).getStuAssess();
                        double stuScoreOfQuestion = 0;
                        double ScoreOfQuestion = 0;
                        for(int c=0;c<sumOfQuestion;c++){
                            stuScoreOfQuestion = stuScoreOfQuestion+Double.valueOf(Control.returnArray(stuAssessOfQuestion,"$、",2)[c]);
                            ScoreOfQuestion = ScoreOfQuestion + InforGuessTesting.getPaperContent().get(i).getScore()/sumOfQuesKong;
                        }

                        if(Control.getCorrectRate((float)stuScoreOfQuestion,(float)ScoreOfQuestion)<0.7){
                            quesIndexViews[j].setQuesIndexStatus(QuesIndexView.STATUS_WRONG);
                        }else{
                            quesIndexViews[j].setQuesIndexStatus(QuesIndexView.STATUS_RIGHT);
                        }

                    } else {
                        //自评为空
                        if (GetStuAnswer(i, j).equals("")) {//学生答案为空
                            quesIndexViews[j].setQuesIndexStatus(QuesIndexView.STATUS_NO_ANSWER);
                        } else {//学生答案不为空
                            int sumOfRight = 0;
                            int sumOfQuestion = Control.backSum(GetAnswer(i,j),"$、")+1;
                            for(int m=0;m<sumOfQuestion;m++){
                                String strQuestionStuAnswer = Control.returnArray(GetStuAnswer(i, j),"$、",2)[m];
                                String strQuestionAnswer = Control.returnArray(GetAnswer(i, j),"$、",2)[m];
                                int sumOfQuestionAnswer = Control.backSum(strQuestionAnswer,"$/")+1;
                                for(int p=0;p<sumOfQuestionAnswer;p++){
                                    if(strQuestionStuAnswer.trim().equals(Control.returnArray(strQuestionAnswer,"$/",2)[p])){
                                        sumOfRight++;
                                        break;
                                    }
                                }
                            }
                            if(Control.getCorrectRate(Float.valueOf(sumOfRight),Float.valueOf(sumOfQuestion))<0.7){
                                quesIndexViews[j].setQuesIndexStatus(QuesIndexView.STATUS_WRONG);
                            }else{
                                quesIndexViews[j].setQuesIndexStatus(QuesIndexView.STATUS_RIGHT);
                            }
                        }

                    }
                }else{
                    //未作答或未提交
                    if (!GetStuAssess(i, j).equals("")) {//自评不为空
                        quesIndexViews[j].setQuesIndexStatus(QuesIndexView.STATUS_ANSWER);
                    } else {//自评为空
                        Log.e("===GetStuAnswer==","===="+GetStuAnswer(i, j));
                        if (GetStuAnswer(i, j).equals("")) {//学生答案为空
                            quesIndexViews[j].setQuesIndexStatus(QuesIndexView.STATUS_NO_ANSWER);
                        } else {//学生答案不为空
                            quesIndexViews[j].setQuesIndexStatus(QuesIndexView.STATUS_ANSWER);
                        }

                    }
                }


//                if(InforGuessTesting.getState()==2) {
//                    //已提交
//                    if (!GetStuAssess(i, j).equals("")) {//自评不为空
//
//                        float fA = Float.valueOf(GetStuAssess(i, j));
//                        float fB = (float) (InforGuessTesting.getPaperContent().get(i).getScore()/sumTotalItemCount);
//
//                        if(Control.getCorrectRate(fA,fB)>=0.7){
//                            quesIndexViews[j].setQuesIndexStatus(QuesIndexView.STATUS_RIGHT);
//                        }else{
//                            quesIndexViews[j].setQuesIndexStatus(QuesIndexView.STATUS_WRONG);
//                        }
//
//                    } else {//自评为空
//                        if (GetStuAnswer(i, j).equals("")) {//学生答案为空
//                            quesIndexViews[j].setQuesIndexStatus(QuesIndexView.STATUS_NO_ANSWER);
//                        } else {//学生答案不为空
//                            if (GetStuAnswer(i, j).equals(GetAnswer(i, j))) {//学生答案与参考答案一致
//                                quesIndexViews[j].setQuesIndexStatus(QuesIndexView.STATUS_RIGHT);
//                            } else {//学生答案与参考答案不一致
//                                quesIndexViews[j].setQuesIndexStatus(QuesIndexView.STATUS_WRONG);
//                            }
//                        }
//
//                    }
//                }else{//未作答或未提交
//                    if (!GetStuAssess(i, j).equals("")) {//自评不为空
//                        quesIndexViews[j].setQuesIndexStatus(QuesIndexView.STATUS_ANSWER);
//                    } else {//自评为空
//                        if (GetStuAnswer(i, j).equals("")) {//学生答案为空
//                            quesIndexViews[j].setQuesIndexStatus(QuesIndexView.STATUS_NO_ANSWER);
//                        } else {//学生答案不为空
//                            quesIndexViews[j].setQuesIndexStatus(QuesIndexView.STATUS_ANSWER);
//                        }
//
//                    }
//                }

                quesIndexViews[j].setQuesIndexText(String.valueOf(j + 1));
                    //BtnQuesNumber[j].setText(String.valueOf(i + 1)+"-"+String.valueOf(j + 1));
//                    BtnQuesNumber[j].setTextSize(Control.dip2px(mContext,6));
                //BtnQuesNumber[j].setTextSize(12);
                final int finalI = i;
                final int finalJ = j;

                quesIndexViews[j].setQuesIndexClickListener(new QuesIndexView.QuesIndexClickListener() {
                    @Override
                    public void onClick(View v) {

                        VpGuessTestingPaper.setCurrentItem(finalI);
//                            Log.e("=====finalJ========","===AA===="+finalJ);
//                            VpAnswer.setCurrentItem(finalJ);

                        Fragment fragment = (Fragment) ((GuessTestingPaperFragmentAdapter) VpGuessTestingPaper.getAdapter()).instantiateItem(VpGuessTestingPaper, finalI);
                        ViewPager childViewPage = (ViewPager) fragment.getView().findViewById(R.id.viewpage_answer);
                        childViewPage.setCurrentItem(finalJ);

                        dismiss();
                    }
                });
                /*BtnQuesNumber[j].setOnClickListener(new OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            VpGuessTestingPaper.setCurrentItem(finalI);
//                            Log.e("=====finalJ========","===AA===="+finalJ);
//                            VpAnswer.setCurrentItem(finalJ);

                            Fragment fragment = (Fragment) ((GuessTestingPaperFragmentAdapter) VpGuessTestingPaper.getAdapter()).instantiateItem(VpGuessTestingPaper, finalI);
                            ViewPager childViewPage = (ViewPager) fragment.getView().findViewById(R.id.viewpage_answer);
                            childViewPage.setCurrentItem(finalJ);

                            dismiss();
                        }
                    });*/
                    RelativeLayout.LayoutParams btnParams = new RelativeLayout.LayoutParams(width / 9, width / 9);

                    if (j % 6 == 0) {
                        k++;
                    }

                    btnParams.leftMargin = ((width) / 6) * (j % 6) + (width / 6 - width / 9) / 2;   //横坐标定位
                    btnParams.topMargin = 20 + (width / 9 + 20) * k;   //纵坐标定位

                    if(strTypeName.equals("看图写句子")||strTypeName.equals("句子填空")|| strTypeName.equals("翻译填空")||
                            strTypeName.equals("听力填空")||strTypeName.equals("阅读填空")|| strTypeName.equals("短文填空")||
                            strTypeName.equals("词汇填空")){


//                        if(!GetStuAssess(i, j).equals("")){
//
//                            int sumOfQuestion = Control.backSum(GetAnswer(i,j),"$、")+1;
//                            String stuAssessOfQuestion = InforGuessTesting.getPaperContent().get(i).getQueList().get(j).getStuAssess();
//                            double stuScoreOfQuestion = 0;
//                            double ScoreOfQuestion = 0;
//                            for(int c=0;c<sumOfQuestion;c++){
//                                stuScoreOfQuestion = stuScoreOfQuestion+Double.valueOf(Control.returnArray(stuAssessOfQuestion,"$、",2)[c]);
//                                ScoreOfQuestion = ScoreOfQuestion + InforGuessTesting.getPaperContent().get(i).getScore()/sumOfQuesKong;
//                            }
//
//                            stuScore = stuScore + stuScoreOfQuestion;
//                        }else{
//
//                            for(int a=0;a<Control.backSum(GetAnswer(i,j),"$、")+1;a++){
//                                String smallQuesStuAnswer = Control.returnArray(GetStuAnswer(i,j),"$、",2)[a];
//                                String smallQuesAnswer = Control.returnArray(GetAnswer(i,j),"$、",2)[a];
//                                for(int b=0;b<Control.backSum(smallQuesAnswer,"$/")+1;b++){
//                                    if(smallQuesStuAnswer.equals(Control.returnArray(smallQuesAnswer,"$/",2)[b])){
//                                        stuScore = stuScore + InforGuessTesting.getPaperContent().get(i).getScore()/sumOfQuesKong;
//                                        break;
//                                    }
//                                }
//                            }
//                        }

                        int sumOfQuestion = Control.backSum(GetAnswer(i,j),"$、")+1;
                        for(int c=0;c<sumOfQuestion;c++){
                            String smallQuesStuAnswer = Control.returnArray(GetStuAnswer(i,j),"$、",2)[c];
                            String smallQuesAnswer = Control.returnArray(GetAnswer(i,j),"$、",2)[c];
                            String smallQuesStuAssess = Control.returnArray(GetStuAssess(i,j),"$、",2)[c];
                            if(!smallQuesStuAssess.equals("")){
                                stuScore = stuScore + Double.valueOf(smallQuesStuAssess);
                            }else{
                                for (int b = 0; b < Control.backSum(smallQuesAnswer, "$/") + 1; b++) {
                                    if (smallQuesStuAnswer.equals(Control.returnArray(smallQuesAnswer, "$/", 2)[b])) {
                                        stuScore = stuScore + InforGuessTesting.getPaperContent().get(i).getScore() / sumOfQuesKong;
                                        break;
                                    }
                                }
                            }
                        }



                    }else if(strTypeName.equals("作文")||strTypeName.equals("翻译题")){

                        if(GetStuAssess(i,j).equals("")){
                            stuScore = stuScore + InforGuessTesting.getPaperContent().get(i).getScore() / sumOfQuesKong;
                        }else{
                            stuScore = stuScore + Double.valueOf(GetStuAssess(i,j));
                        }

                    }else if(strTypeName.equals("阅读简答")){

                        if(GetStuAssess(i,j).equals("")){
                            stuScore = stuScore + InforGuessTesting.getPaperContent().get(i).getScore() / sumOfQuesKong;
                        }else{
                            stuScore = stuScore + Double.valueOf(GetStuAssess(i,j));
                        }

                    }else{
                        if(InforGuessTesting.getPaperContent().get(i).getQueList().get(j).getStuAnswer().
                                equals(InforGuessTesting.getPaperContent().get(i).getQueList().get(j).getAnswer())){
                            stuScore = stuScore+InforGuessTesting.getPaperContent().get(i).getScore()/sumTotalItemCount;
                        }
                    }
                Log.e("==000=====","====TvTypeName==="+strTypeName+"=====stuScore====="+stuScore);

                    //RLayoutQuesList[i].addView(BtnQuesNumber[j],btnParams);
                RLayoutQuesList[i].addView(quesIndexViews[j],btnParams);

            }

            allScore = allScore+InforGuessTesting.getPaperContent().get(i).getScore();

            LayoutAnswerSheet.addView(RLayoutQuesList[i]);
        }

        /*********************************************/
        /*********************************************/
        if(InforGuessTesting.getState()!=2){
            TvTitle.setText("答题卡");
            LayoutAssess.setVisibility(View.GONE);
            BtnCheckAllAnalysis.setVisibility(View.GONE);
        }else{
            TvTitle.setText("练习报告");
            LayoutAssess.setVisibility(View.VISIBLE);

            TvAllScore.setText(stuScore+"分/"+allScore+"分");
            int useTime = InforGuessTesting.getDuration();
            int hour = useTime/3600;
            int minute = useTime/60%60;
            int second = useTime%60;
            String useTimeLong = "";
            if(hour>0){
                useTimeLong = hour+"时"+minute+"分"+second+"秒";
            }else{
                if(minute>0){
                    useTimeLong = minute+"分"+second+"秒";
                }else{
                    useTimeLong = second+"秒";
                }
            }
            TvUseTime.setText(useTimeLong);
            if(isfirstSubmit) {
                BtnCheckAllAnalysis.setVisibility(View.VISIBLE);
            }else{
                BtnCheckAllAnalysis.setVisibility(View.GONE);
            }
            BtnCheckAllAnalysis.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
//                    checkAllAnalysisListener.onClick();
                    dismiss();
//                    VpGuessTestingPaper.setCurrentItem(0);
                }
            });
        }
        /*********************************************/
        /*********************************************/

    }

    /*
    * 获取学生答案
    * */
    private String GetStuAnswer(int i,int j){
        String strStuAnswer = InforGuessTesting.getPaperContent().get(i).getQueList().get(j).getStuAnswer();
        strStuAnswer = strStuAnswer.replaceAll("$、","");
        strStuAnswer = strStuAnswer.replaceAll("$/","");
        return strStuAnswer;
    }

    /*
    * 获取参考答案
    * */
    private String GetAnswer(int i,int j){
        return InforGuessTesting.getPaperContent().get(i).getQueList().get(j).getAnswer();
    }

    /*
    * 获取自评或及机评结果
    * */
    private String GetStuAssess(int i,int j){
        return InforGuessTesting.getPaperContent().get(i).getQueList().get(j).getStuAssess();
    }

//    public interface CheckAllAnalysisListener{
//        void onClick();
//    }
//
//    private CheckAllAnalysisListener checkAllAnalysisListener;
//
//    public void setCheckAllAnalysis(CheckAllAnalysisListener listener){
//        this.checkAllAnalysisListener = listener;
//    }

}